package com.milkway.auth;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.milkway.Constants;

public class AuthenticationFilter implements Filter {
  
  private String[] notRequiredAuthPages = null;
  private String redirectPage = null;

  @Override
  public void destroy() {
    this.notRequiredAuthPages = null;
    this.redirectPage = null;
  }

  @Override
  public void doFilter(ServletRequest req, ServletResponse res,
      FilterChain chain) throws IOException, ServletException {
    HttpServletRequest httpReq = (HttpServletRequest)req;
    HttpServletResponse httpRes = (HttpServletResponse)res;
    
    boolean skip = !checkIfRequiredAuth(httpReq) || checkIfLoggedIn(httpReq);
    
    if (skip) {
      chain.doFilter(req, res);
    } else {
      httpRes.sendRedirect(redirectPage);
    }
  }

  private boolean checkIfLoggedIn(HttpServletRequest httpReq) {
    Object value = httpReq.getSession().getAttribute(Constants.HAS_LOGGED_IN);
    System.out.println("hasLoggedIn : " + value);
    if (value != null) {
      if ((Boolean) value) {
        return true;
      }
    }
    return false;
  }

  private boolean checkIfRequiredAuth(HttpServletRequest httpReq) {
    String path = httpReq.getServletPath();
    
    //only jsp files are required authentication
    if (!path.endsWith(".jsp")) {
      return false;
    }
    
    for (String p : notRequiredAuthPages) {
      if (path.endsWith(p)) {
        return false;
      }
    }
    
    return true;
  }

  @Override
  public void init(FilterConfig config) throws ServletException {
    String notRequiredAuthString = config.getInitParameter("notRequiredAuth");
    notRequiredAuthPages = notRequiredAuthString.split(",");
    redirectPage = config.getServletContext().getContextPath() + config.getInitParameter("redirectPage");
  }

}
